package com.koron.css2.serviceManage.utils;

import com.koron.css2.serviceManage.bean.RecordBean;
import com.koron.css2.serviceManage.bean.TServiceLog;
import com.koron.css2.serviceManage.bean.TServicePageBean;
import com.koron.css2.serviceManage.service.ServerService;
import com.koron.css2.serviceManage.service.ServiceLogService;
import com.koron.css2.serviceManage.service.ServicePageService;
import com.mysql.cj.util.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.ADOConnection;

public class PageDetailLogHandler {

	private static Logger logger = LogManager.getLogger(PushBlockQueueHandler.class);
	private ServerService service = new ServerService();
	private ServicePageService pageService = new ServicePageService();
	private ServiceLogService logService = new ServiceLogService();

	/**
	 * 记录调用页面和修改调用次数
	 */
	public void recordPage(RecordBean record) {
		TServicePageBean pageBean = new TServicePageBean();
		pageBean.setServiceCode(record.getServiceCode());
		pageBean.setPageAddr(record.getPageAddr());
		pageBean.setCreateName(record.getCreateName());
		ADOConnection.runTask(service, "updateCountByServiceCode", Integer.class, record.getServiceCode());
		ADOConnection.runTask(pageService, "insPageToServices", Integer.class, pageBean);
	}

	/**
	 * 记录服务调用日志
	 */
	public void recordLog(RecordBean record) {
		TServiceLog log = new TServiceLog();
		log.setServiceCode(record.getServiceCode());
		log.setCaller(record.getCaller());
		log.setCreateTime(record.getCreateTime());
		log.setIpAddr(record.getIpAddr());
		log.setComments(record.getComments());
		log.setBrowserType(record.getBrowserType());
		//超过长度不保存
		log.setRequestJson(record.getRequest().length()>1500?record.getRequest().substring(0,1500)+"...":record.getRequest());
		log.setResponseJson(record.getResponse().length()>3000?record.getResponse().substring(0,3000)+"...":record.getResponse());
		if (StringUtils.isNullOrEmpty(record.getWaterGroup())) {
			log.setWaterGroup("运维平台");
		} else {
			log.setWaterGroup(record.getWaterGroup());
		}
		ADOConnection.runTask(logService, "addLog", Integer.class, log);
	}

	/**
	 * 记录文件日志
	 */
	public void recordLogFile(RecordBean record) {
		String descPattern = "调用人:{},服务标识:{},客户端IP地址:{},浏览器:{},输入参数:{},返回结果:{}";
		logger.debug(descPattern, record.getCaller(), record.getServiceCode(), record.getIpAddr(),
				record.getBrowserType(), record.getRequest(), record.getResponse());
	}
}
